<?php
// +----------------------------------------------------------------------
// | 中犇单商户
// +----------------------------------------------------------------------
// | Copyright (c) 2019-2021 中犇科技 All rights reserved.
// +----------------------------------------------------------------------


namespace app\operation\admin;

use app\admin\admin\Base;
use app\operation\model\Coupon as CouponModel;
use app\goods\model\Category;
use app\goods\model\Goods;
use app\operation\model\CouponRecord;
use app\user\model\User as UserModel;
use service\Format;

/**
 * 优惠券控制器
 * Class Coupon
 * @package app\admin\controller
 */
class Coupon extends Base
{

    /**
     * 优惠券列表
     * @return \think\response\View
     * @throws \think\exception\DbException
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */

    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        // 查询
        $map = $this->getMap();
        // 排序
        $order = $this->getOrder('id desc');      
        // 数据列表
        $data_list = CouponModel::where($map)->where("is_delete",0)->order($order)->paginate();

        $fields = [
            ['id', 'ID'],
            ['name', lang('优惠券名称')],
            ['start_time', lang('开始领取时间'), 'callback', function ($data) {
                return date('Y-m-d', $data) . ' 00:00:00';
            }],
            ['end_time', lang('领取结束时间'), 'callback', function ($v) {
                return date('Y-m-d', $v) . ' 23:59:59';
            }],
            ['money', lang('面额')],
            ['min_order_money', lang('最低使用金额')],
            ['valid_day', lang('有效天数')],
            ['stock', lang('总张数')],
            ['last_stock', lang('剩余张数')],
            ['method', lang('领取方式'), 'status', '', [lang('系统发放'), lang('首页弹窗'), lang('手动领取')]],
            ['create_time', lang('创建时间'), '', '', '', 'text-center'],
            ['status', lang('状态'), 'status', '', [lang('未开启'), lang('可领取'), lang('已领完')], 'text-center'],
            ['right_button', lang('操作'), 'btn', '', '', 'text-center']
        ];

        return Format::ins()//实例化
            ->hideCheckbox()
            ->addColumns($fields)//设置字段
            ->setTopButtons($this->top_button)
            ->setRightButton(['title' => lang('领取记录'), 'href' => ['receiving', ['id' => '__id__']], 'icon' => 'fa fa-list pr5', 'class' => 'btn btn-xs mr5 btn-success '])
            ->setRightButton(['title' => lang('手动发放'), 'href' => ['send_coupon', ['id' => '__id__']], 'icon' => 'fa fa-send-o pr5', 'class' => 'btn btn-xs mr5 btn-success '])
            ->setRightButtons($this->right_button)
            ->setData($data_list)//设置数据
            ->fetch();//显示
    }

    /**
     * 添加优惠券
     * @return void
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    public function add()
    {
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
//            echo '<pre>';
//            print_r($data);die;
            $data['last_stock'] = $data['stock'];
            // 验证
            $result = $this->validate($data, 'Coupon');
            if (true !== $result) {
                $this->error($result);
            }

            $data['start_time'] = strtotime($data['start_time'] . ' 00:00:00');
            $data['end_time'] = strtotime($data['end_time'] . ' 23:59:59');
            if ($data['money'] >= $data['min_order_money']) {
                $this->error(lang('面值不可小于最低使用金额'));
            }          

            if( $data['start_time'] >=  $data['end_time']){
               $this->error(lang('开始时间不可小于结束时间')); 
            }
            if( time() >=  $data['end_time']){
               $this->error(lang('结束时间应是未来时间')); 
            }
            if ($data['goods_id']) {
                $goodsinfo = Goods::where(['id'=>$data['goods_id']])->field('name,shop_price')->find();
                if (bccomp($goodsinfo['shop_price'],$data['min_order_money'],2) < 0) {
                     $this->error(lang('选择的商品定价小于优惠券最低使用金额'));
                }
                $data["content"] = $data["content"] ?: "指定商品可用";
                $data['cid'] = 0;
             }             
             else if ($data['cid']) {
                $cate = Category::where(['id'=>$data['cid']])->field('name')->find();
                if (!$cate) {
                     $this->error(lang('选择的分类不正确'));
                }
                $data["content"] = $data["content"] ?: "仅限".$cate["name"]."分类可用";              
            }else{
                $data["content"] =  $data["content"] ?: "全场可用";
            }

            if ($res = CouponModel::create($data)) {
                $this->success(lang('新增成功'), cookie('__forward__'));
            } else {
                $this->error(lang('新增失败'));
            }
        }
        $category = Category::getTree(0,"全品类");
        

        $fields = [
            ['type' => 'text', 'name' => 'name', 'title' => lang('优惠券名称')],
     
            ['type' => 'select', 'name' => 'cid', 'title' => lang('商品分类'), 'extra' => $category, 'tips' => '仅限品类优惠券使用，请选择三级分类，如已设置商品，则分类无效'],            
            [
                'type' => 'selectajax',
                'name' => 'goods_id',
                'title' => lang('所属商品'), 
                'url' => url( 'getGoodsList'), 
                'tips' => '仅限单品优惠券使用，如已设置商品，则分类无效,优惠券面额不可超过商品售价',
                "text"=>"全部商品"
            ],

            ['type' => 'date', 'name' => 'start_time', 'title' => lang('开始领取时间'), 'tips' => ''],
            ['type' => 'date', 'name' => 'end_time', 'title' => lang('领取结束时间'), 'tips' => ''],
            ['type' => 'text', 'name' => 'money', 'title' => lang('面额'), 'tips' => ''],
            ['type' => 'number', 'name' => 'min_order_money', 'title' => lang('最低使用金额'), 'tips' => lang('不用填写单位，只需填写具体数字')],
            ['type' => 'number', 'name' => 'valid_day', 'title' => lang('有效天数'), 'tips' => ''],
            ['type' => 'number', 'name' => 'stock', 'title' => lang('总张数'), 'tips' => lang('不用填写单位，只需填写具体数字')],
            ['type' => 'radio', 'name' => 'method', 'title' => lang('领取方式'), 'extra' => [lang('系统发放'), lang('首页弹窗'), lang('手动领取')], 'value' => 0],
            ['type' => 'radio', 'name' => 'status', 'title' => lang('状态'), 'tips' => '', 'extra' => [lang('关闭'), lang('可领取')], 'value' => 0],
            ['type' => 'text', 'name' => 'content', 'title' => lang('请填写优惠券内容'), 'tips' => '全场通用/指定XX商品可用/指定XX分类可用']
        ];

        $this->assign('page_title', lang('新增优惠券'));
        $this->assign('form_items', $fields);
        $this->assign('set_script', ['/static/plugins/layer/laydate/laydate.js']);
        return $this->fetch('admin@public/add');
    }

    public function getGoodsList($cid = '')
    {
        $key = input('key/s', '');
        if ($key == '') {
            return '';
        }
        $where[] = ["goods.status", "=", 1];
        $where[] = ["goods.is_sale", "=", 1]; 
        $where[] = ['goods.is_delete', '=', 0];     
        $where[] = ['goods.name', 'like', "%".$key."%"];   
        // 数据列表
        $data_list = Goods::view("goods","id,name,shop_price,thumb")
                ->view("goods_category","name as cate_name","goods.cid = goods_category.id","left")
                ->where($where)
                ->paginate(20);
        $results = [];
        foreach ($data_list as $v) {
            $str = '<img src="'.get_thumb($v["thumb"]).'" height="28px" style="float:left;margin-right:10px"/>【'.$v['cate_name']  . '】/' .$v['id'] . '/' . $v['name'] . '/￥' . $v['shop_price'] ;
            $results[] = ['id' => $v['id'], 'text' => $str];
        }
        $data['results'] = $results;
        $data['pagination'] = $data_list->currentPage() == $data_list->lastPage() ? ['more' => true] : ['more' => false];
        return json($data, JSON_UNESCAPED_UNICODE);
    }
    /**
     * 编辑优惠券
     * @param int $id 优惠券id
     * @return \think\response\View
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    public function edit($id = 0)
    {
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            
            // 验证
            $result = $this->validate($data, 'Coupon');
            if (true !== $result) {
                $this->error($result);
            }

            $data['start_time'] = strtotime($data['start_time'] . ' 00:00:00');
            $data['end_time'] = strtotime($data['end_time'] . ' 23:59:59');
            if ($data['money'] >= $data['min_order_money']) {
                $this->error(lang('面值不可小于最低使用金额'));
            }          

            if( $data['start_time'] >=  $data['end_time']){
               $this->error(lang('开始时间不可小于结束时间')); 
            }
            if( time() >=  $data['end_time']){
               $this->error(lang('结束时间应是未来时间')); 
            }
           if ($data['goods_id']) {
                $goodsinfo = Goods::where(['id'=>$data['goods_id']])->field('name,shop_price')->find();
                if (bccomp($goodsinfo['shop_price'],$data['min_order_money'],2) < 0) {
                     $this->error(lang('选择的商品定价小于优惠券最低使用金额'));
                }
                $data["content"] = $data["content"] ?: "指定商品可用";
                $data['cid'] = 0;
             }             
             else if ($data['cid']) {
                $cate = Category::where(['id'=>$data['cid']])->field('name')->find();
                if (!$cate) {
                     $this->error(lang('选择的分类不正确'));
                }
                $data["content"] = $data["content"] ?: "仅限".$cate["name"]."分类可用";              
            }else{
                $data["content"] =  $data["content"] ?: "全场可用";
            }


            if (CouponModel::update($data)) {
                // 记录行为
                action_log('coupon_edit', 'operation_coupon', $id, UID, $data['name']);
                $this->success(lang('编辑成功'), 'index');
            } else {
                $this->error(lang('编辑失败'));
            }
        }

        if (!$id) {
            $this->error(lang('参数错误'));
        }

        // 读取优惠券信息
        $info = CouponModel::get($id);
        $info['start_time'] = date('Y-m-d', $info['start_time']);
        $info['end_time'] = date('Y-m-d', $info['end_time']);
 
        $category = Category::getTree(0,'全部分类');
        if($info["cid"] && !isset($category[$info["cid"]])){
            $info["cid"] = 0;
            $category[0] = "分类已失效";
        }
        $name = "全部商品";
        if($info["goods_id"]){
           $goods = Goods::view("goods","id,name,shop_price,thumb")
                ->view("goods_category","name as cate_name","goods.cid = goods_category.id","left")
                ->where("goods.id",$info["goods_id"])
                ->find();
           if(!$goods){
               $info["goods_id"] = 0;
               $name = "商品已失效";
           }else{
               $name = '<img src="'.get_thumb($goods["thumb"]).'" height="28px" style="float:left;margin-right:10px"/>【'.$goods['cate_name']  . '】/' .$goods['id'] . '/' . $goods['name'] . '/￥' . $goods['shop_price'] ;
           }
        }
        
        $fields = [
            ['type' => 'hidden', 'name' => 'id'],
            ['type' => 'text', 'name' => 'name', 'title' => lang('优惠券名称')],
            ['type' => 'select', 'name' => 'cid', 'title' => lang('商品分类'), 'extra' => $category, 'tips' => '仅限品类优惠券使用，请选择三级分类，如已设置商品，则分类无效'],            
            [
                'type' => 'selectajax',
                'name' => 'goods_id',
                'title' => lang('所属商品'), 
                'url' => url( 'getGoodsList'), 
                'tips' => '仅限单品优惠券使用，如已设置商品，则分类无效,优惠券面额不可超过商品售价',
                "text"=> $name
            ],
            ['type' => 'date', 'name' => 'start_time', 'title' => lang('开始领取时间'), 'tips' => ''],
            ['type' => 'date', 'name' => 'end_time', 'title' => lang('领取结束时间'), 'tips' => ''],
            ['type' => 'text', 'name' => 'money', 'title' => lang('面额'), 'tips' => ''],
            ['type' => 'number', 'name' => 'min_order_money', 'title' => lang('最低使用金额'), 'tips' => lang('不用填写单位，只需填写具体数字')],
            ['type' => 'number', 'name' => 'valid_day', 'title' => lang('有效天数'), 'tips' => ''],
            ['type' => 'number', 'name' => 'stock', 'title' => lang('总张数'), 'tips' => lang('不用填写单位，只需填写具体数字')],
            ['type' => 'radio', 'name' => 'method', 'title' => lang('领取方式'), 'extra' => [lang('系统发放'), lang('首页弹窗'), lang('手动领取')]],
            ['type' => 'radio', 'name' => 'status', 'title' => lang('状态'), 'tips' => '', 'extra' => [lang('关闭'), lang('可领取')]],
            ['type' => 'text', 'name' => 'content', 'title' => lang('请填写优惠券内容'), 'tips' => '全场通用/指定XX商品可用/指定XX分类可用']
        ];

        $this->assign('page_title', lang('编辑优惠券'));
        $this->assign('set_script', ['/static/plugins/layer/laydate/laydate.js']);
        $this->assign('form_items', $this->setData($fields, $info));
        return $this->fetch('admin@public/edit');
    }
     /**
     * 优惠券审核
     * @author php迷途小书童
     * @created 2021/1/28 15:43
     */
    public function delete($ids = ''){

        empty($ids) && $this->error('缺少主键');
        
        CouponModel::delIds($ids);    
        $this->success('操作成功');       
    }
   /**
     * 优惠券领取记录
     * @param int $id 优惠券id
     * @return mixed
     * @throws \think\exception\DbException
     * @author 似水星辰 [ 2630481389@qq.com ]
     */
    public function receiving($id = 0)
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        // 查询
        if($id){
            $map['cr.cid'] = $id;
        }
        $this->getMap(['accepter']);
        $accepter = input('param.accepter');
        if($accepter){
            $map['cr.user_id']=UserModel::name('user')->where([['user_nickname','like','%'.$accepter.'%']])->value('id');
        }
        // 排序
        $order = $this->getOrder('cr.start_time desc');
        // 数据列表
        $data_list = CouponRecord::alias('cr')->join('operation_coupon c','cr.cid=c.id')
                ->where($map)
                ->field('cr.*,c.name,c.money,c.min_order_money')
                ->order($order)
                ->paginate();

        $fields = [
            //['id', 'ID'],
            ['name', '优惠券名称'],
            ['user_id', '领取人','callback','get_nickname'],
            ['start_time', '领取时间', 'callback', function ($data) {
                return date('Y-m-d H:i:s', $data);
            }, '', 'text-center'],
            ['end_time', '过期时间', 'callback', function ($v) {
                return date('Y-m-d H:i:s', $v);
            }, '', 'text-center'],
            ['money', '面额'],
            ['min_order_money', '最低使用金额'],
            ['status', '状态', 'status', '', ['已过期', '未使用', '占用中','已使用','已失效'], 'text-center'],
            ['right_button', '操作', 'btn', '', '', 'text-center']
        ];
        $search_fields = [
            ['accepter', '领取人', 'text'],
        ];
        return Format::ins()//实例化
            ->addColumns($fields)//设置字段
            ->setTopSearch($search_fields)
            ->setRightButton(['ident'=>'delete','title' => '删除优惠券', 'href' => ['delete_coupon_record', ['id' => '__id__']],  'class' => 'btn btn-xs btn-danger font12 ajax-get confirm'])
            ->replaceRightButton(['status'=>['in',[2,3]]],'','delete')
            ->hideCheckbox()          
            ->setData($data_list)//设置数据
            ->fetch();//显示
    }

    /** 删除会员的优惠券
     * @param $id
     * @return void
     * @author 刘明美 [ liumingmei@zhongbenjituan.com ]
     */
    public function delete_coupon_record($id)
    {
        if (!$id) {
            $this->error(lang('参数错误'));
        }

        $res = CouponRecord::where('id', $id)->delete();
        if ($res) {
            $this->success(lang('删除成功'));
        }

        $this->error(lang('删除失败'));
    }

   /**
     * 发放优惠券
     * @param $id
     * @author 风情云淡
     * @return mixed
     */
    function send_coupon($id = 0){
        if(!$id){
            $this->error("参数错误");
        } 
        if($this->request->isPost()){
            $data = $this->request->post();
            if(!$data["user_id"]){
                $this->error("请选择会员");
            }   
            $user = UserModel::get($data["user_id"]);
            if(!$user){
                $this->error("会员选择错误");
            }
            try{
                CouponRecord::sendUserCoupon($user["id"], $id ,0);
            }catch(\Exception $e){
                $this->error($e->getMessage());  
            }           
            $this->success("发放成功",url('receiving',['id'=>$id]));  
        }
        //获得用户信息
        $fields = [
            ['type' => 'selectajax', 'name' => 'user_id',"title"=>"会员ID/昵称/手机号"],          
        ];
        $this->assign('page_title', '发送优惠券');
        $this->assign('form_items', $fields);
        return $this->fetch('admin@public/add');
    }
}
